<template>
  <div>
    <CommonPanel :title="$t('portalAuth.visualSetting')">
      <!-- customize -->
      <!-- <a-button @click="savePortal"></a-button> -->
      <div class="content">
        <div class="left">
          <a-form-model
            labelAlign="left"
            :model="form"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-model-item label="Logo">
              <a-switch v-model="form.hasLogo" />
            </a-form-model-item>
            <a-form-model-item
              v-if="form.hasLogo"
              :label="$t('portalAuth.logoImage')"
            >
              <a-upload
                :file-list="fileList"
                :beforeUpload="beforeUploadLogo"
                accept=".jpg,.png,.gif"
              >
                <a-button> {{ $t('common.upload') }} </a-button>
              </a-upload>
            </a-form-model-item>
            <a-form-model-item
              v-if="form.hasLogo"
              :label="$t('portalAuth.logoPosition')"
            >
              <a-slider
                v-model="form.style.logoPosition"
                :marks="positionMarks"
                :default-value="0"
                :step="10"
                :max="50"
              />
            </a-form-model-item>

            <!-- 背景 start -->
            <a-form-model-item>
              <rj-space slot="label">
                <span>{{ $t('portalAuth.background') }} </span>
                <a-tooltip
                  placement="topLeft"
                  :title="$t('portalAuth.imgTip', { size: 2.5 })"
                  arrow-point-at-center
                >
                  <icon-font type="ic-help" class="ic-help-tip" />
                </a-tooltip>
              </rj-space>
              <a-radio-group v-model="form.backgroundType">
                <a-radio value="image">
                  {{ $t('portalAuth.picture') }}
                </a-radio>
                <a-radio value="color">
                  {{ $t('portalAuth.solidColor') }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              v-if="form.backgroundType === 'image'"
              :label="$t('portalAuth.bgImg')"
            >
              <div class="scene-bg-wrapper">
                <div
                  v-for="(item, index) in defaultBackgroundImage"
                  :key="index"
                  @click="onSelectSceneBg(item)"
                  :style="
                    index === defaultImgId
                      ? 'border: 2px solid #548dff;border-radius: 5px;'
                      : ''
                  "
                >
                  <img
                    :src="item.miniUrl"
                    style="width: 50px; height: 70px"
                    :title="item.tooltip"
                  />
                </div>
              </div>
              <a-upload
                :file-list="fileList2"
                :beforeUpload="beforeUploadBg"
                @change="onChangeBackground"
                accept=".jpg,.png,.gif"
              >
                <a-button> {{ $t('common.upload') }} </a-button>
              </a-upload>
            </a-form-model-item>
            <a-form-model-item
              v-if="form.backgroundType === 'color'"
              :label="$t('portalAuth.bgColor')"
            >
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.backgroundColor"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.backgroundColor" />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>

            <!-- 背景遮罩 -->
            <a-form-model-item :label="$t('portalAuth.bgMaskColor')">
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.backgroundMaskColor"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.backgroundMaskColor" />
                  </a-col>
                  <a-col :span="5">
                    <a-input-number
                      v-model="form.style.backgroundMaskOpacity"
                      :min="0"
                      :max="100"
                      :formatter="(value) => `${value}%`"
                      :parser="(value) => value.replace('%', '')"
                      style="width: 80px"
                    />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>

            <a-form-model-item>
              <rj-space slot="label">
                <span>{{ $t('portalAuth.welcomeMsg') }} </span>
                <a-tooltip
                  placement="topLeft"
                  :title="$t('portalAuth.imgTip', { size: 1.5 })"
                  arrow-point-at-center
                >
                  <icon-font type="ic-help" class="ic-help-tip" />
                </a-tooltip>
              </rj-space>
              <a-radio-group
                v-model="form.portalSubForm.welcomeType"
                @change="onChangePortal($event, 'welcomeType')"
              >
                <a-radio value="text"> {{ $t('portalAuth.text') }} </a-radio>
                <a-radio value="image">
                  {{ $t('portalAuth.picture') }}
                </a-radio>
                <!-- <a-radio :value="3"> video </a-radio> -->
              </a-radio-group>
            </a-form-model-item>

            <!-- tab功能 -->
            <div class="tabs">
              <a-tabs
                v-model="currentLangCode"
                type="editable-card"
                @edit="onEditLangTab"
                @change="onChangeLangTab"
                hideAdd
              >
                <a-tab-pane
                  v-for="item in selectedLangs"
                  :key="item.code"
                  :tab="item.name"
                  :closable="selectedLangs.length > 1"
                >
                </a-tab-pane>
              </a-tabs>
              <a-popover
                class
                placement="bottomRight"
                v-if="selectedLangs.length < 3"
              >
                <div
                  slot="content"
                  style="cursor: pointer"
                  :style="getSelectedClass(item)"
                  v-for="(item, index) in portalLangs"
                  :key="index"
                  @click="onClickLangPop(item)"
                >
                  {{ item.name }}
                </div>
                <a-button type="link" class="preview-add-lang">+</a-button>
              </a-popover>
            </div>

            <!-- 语言切换的tab部分 -->
            <div class="lang-wrapper">
              <a-form-model-item :label="$t('portalAuth.defaultLang')">
                <a-switch
                  v-model="form.portalSubForm.isShowLang"
                  @change="onChangeShowLang"
                ></a-switch>
              </a-form-model-item>
              <a-form-model-item
                v-if="form.portalSubForm.welcomeType === 'image'"
                :label="$t('portalAuth.welcomeImg')"
              >
                <a-upload
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  :multiple="true"
                  :file-list="fileList3"
                  :beforeUpload="beforeUploadWelcomeImg"
                >
                  <a-button>{{ $t('common.upload') }} </a-button>
                </a-upload>
              </a-form-model-item>
              <a-form-model-item
                v-if="form.portalSubForm.welcomeType === 'text'"
                :label="$t('portalAuth.welcomeText')"
              >
                <a-textarea
                  v-model="form.portalSubForm.welcome"
                  @change="onChangePortal($event, 'welcome')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :rows="2"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item :label="$t('portalAuth.marketingMsg')">
                <a-textarea
                  v-model="form.portalSubForm.marketMessage"
                  @change="onChangePortal($event, 'marketMessage')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :rows="2"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item :label="$t('portalAuth.tAndC')">
                <a-textarea
                  v-model="form.portalSubForm.tc"
                  @change="onChangePortal($event, 'tc')"
                  :rows="2"
                  :maxLength="10000"
                />
              </a-form-model-item>

              <a-form-model-item v-show="includeRegister">
                <span slot="label">
                  {{ $t('portalAuth.privacyDisclaimer') }}
                  <a-tooltip>
                    <template slot="title">
                      {{ $t('portalAuth.protectTip') }}
                    </template>
                    <a-icon type="question-circle-o" />
                  </a-tooltip>
                </span>
                <a-checkbox
                  :checked="checkProtection"
                  @change="handlecheckProtection"
                >
                  {{ $t('portalAuth.readDisclaimer1') }}
                  <b
                    @click="showPersonDataModal"
                    style="
                      text-decoration: underline;
                      color: #056de8;
                      cursor: pointer;
                    "
                  >
                    {{ $t('portalAuth.readDisclaimer2') }}
                  </b>
                  {{ $t('portalAuth.readDisclaimer3') }}
                </a-checkbox>
                <div
                  class="div-textarea"
                  :contenteditable="false"
                  :class="[
                    checkProtection && !form.portalSubForm.regDisclaimerContent
                      ? 'disclaimer-warning'
                      : 'disclaimer-content',
                  ]"
                >
                  <div
                    @click="showDisclaimerModal()"
                    style="text-decoration: underline; cursor: pointer"
                  >
                    <span v-if="!form.portalSubForm.regDisclaimerContent">
                      {{ $t('portalAuth.protectNotNull2') }}
                    </span>
                    <span v-else>
                      {{ form.portalSubForm.regDisclaimerTitle }}
                    </span>
                  </div>
                </div>
              </a-form-model-item>
              <a-form-model-item :label="$t('portalAuth.copy')">
                <a-input
                  v-model="form.portalSubForm.copyRight"
                  @change="onChangePortal($event, 'copyRight')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>

              <h3 v-show="authTypes.includes('PASS')">
                {{ $t('portalAuth.onClick') }}
              </h3>
              <a-form-model-item
                :label="$t('portalAuth.loginBtn')"
                v-show="authTypes.includes('PASS')"
              >
                <a-input
                  v-model="form.portalSubForm.oneclickBtnTxt"
                  @change="onChangePortal($event, 'oneclickBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>

              <!-- voucher -->
              <h3 v-show="authTypes.includes('VOUCHER')">
                {{ $t('userManage.tabVoucher') }}
              </h3>
              <a-form-model-item
                :label="$t('portalAuth.title')"
                v-show="authTypes.includes('VOUCHER')"
              >
                <a-input
                  v-model="form.portalSubForm.voucherInputTitle"
                  @change="onChangePortal($event, 'voucherInputTitle')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.codePc')"
                v-show="authTypes.includes('VOUCHER')"
              >
                <a-input
                  v-model="form.portalSubForm.accesscodePlacehold"
                  @change="onChangePortal($event, 'accesscodePlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.loginBtn')"
                v-show="authTypes.includes('VOUCHER')"
              >
                <a-input
                  v-model="form.portalSubForm.voucherLoginBtnTxt"
                  @change="onChangePortal($event, 'voucherLoginBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.switchBtn')"
                v-show="authTypes.includes('VOUCHER')"
              >
                <a-input
                  v-model="form.portalSubForm.voucherBtnTxt"
                  @change="onChangePortal($event, 'voucherBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>

              <!-- account -->
              <h3 v-show="authTypes.includes('FIXACCOUNT')">
                {{ $t('account.account') }}
              </h3>
              <a-form-model-item
                :label="$t('portalAuth.title')"
                v-show="authTypes.includes('FIXACCOUNT')"
              >
                <a-input
                  v-model="form.portalSubForm.accountInputTitle"
                  @change="onChangePortal($event, 'accountInputTitle')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.accountPc')"
                v-show="authTypes.includes('FIXACCOUNT')"
              >
                <a-input
                  v-model="form.portalSubForm.accountPlacehold"
                  @change="onChangePortal($event, 'accountPlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.pwdPc')"
                v-show="authTypes.includes('FIXACCOUNT')"
              >
                <a-input
                  v-model="form.portalSubForm.passwordPlacehold"
                  @change="onChangePortal($event, 'passwordPlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.loginBtn')"
                v-show="authTypes.includes('FIXACCOUNT')"
              >
                <a-input
                  v-model="form.portalSubForm.accountLoginBtnTxt"
                  @change="onChangePortal($event, 'accountLoginBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.switchBtn')"
                v-show="authTypes.includes('FIXACCOUNT')"
              >
                <a-input
                  v-model="form.portalSubForm.accountBtnTxt"
                  @change="onChangePortal($event, 'accountBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>

              <!-- sms -->
              <h3 v-show="authTypes.includes('SMS')">SMS</h3>
              <a-form-model-item
                :label="$t('portalAuth.title')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phoneInputTitle"
                  @change="onChangePortal($event, 'phoneInputTitle')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.phonePc')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phonePlacehold"
                  @change="onChangePortal($event, 'phonePlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.codePc')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phoneCodePlaceholder"
                  @change="onChangePortal($event, 'phoneCodePlaceholder')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.CodeBtn')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phoneCodeGetTip"
                  @change="onChangePortal($event, 'phoneCodeGetTip')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.loginBtn')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phoneLoginBtnTxt"
                  @change="onChangePortal($event, 'phoneLoginBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.switchBtn')"
                v-show="authTypes.includes('SMS')"
              >
                <a-input
                  v-model="form.portalSubForm.phoneBtnTxt"
                  @change="onChangePortal($event, 'phoneBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>

              <!-- register -->
              <h3 v-show="authTypes.includes('REGISTER')">
                {{ $t('portalAuth.registerAuth') }}
              </h3>
              <a-form-model-item
                :label="$t('portalAuth.title')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerInputTitle"
                  @change="onChangePortal($event, 'registerInputTitle')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('common.email')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerEmailPlacehold"
                  @change="onChangePortal($event, 'registerEmailPlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('userManage.phone')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerPhonePlacehold"
                  @change="onChangePortal($event, 'registerPhonePlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('internetuser.userName')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerUserPlacehold"
                  @change="onChangePortal($event, 'registerUserPlacehold')"
                  :placeholder="$t('userManage.nameLengthTip')"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.registerBtn')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerLoginBtnTxt"
                  @change="onChangePortal($event, 'registerLoginBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                />
              </a-form-model-item>
              <a-form-model-item
                :label="$t('portalAuth.switchBtn')"
                v-show="authTypes.includes('REGISTER')"
              >
                <a-input
                  v-model="form.portalSubForm.registerBtnTxt"
                  @change="onChangePortal($event, 'registerBtnTxt')"
                  :placeholder="$t('userManage.nameLengthTip')"
                  :maxLength="60"
                />
              </a-form-model-item>
            </div>
            <!--广告开始-->
            <div style="border-bottom: 1px solid #e8e8e8; margin-bottom: 12px">
              <a-form-model-item>
                <rj-space slot="label">
                  <span>{{ $t('portalAuth.advanvture') }} </span>
                  <a-tooltip
                    placement="topLeft"
                    :title="$t('portalAuth.advanvturetip')"
                    arrow-point-at-center
                  >
                    <icon-font type="ic-help" class="ic-help-tip" />
                  </a-tooltip>
                </rj-space>
                <a-switch v-model="form.portalads.adsStatus"></a-switch>
              </a-form-model-item>
              <template v-if="form.portalads.adsStatus">
                <a-form-model-item :label="$t('portalAuth.advanvtureType')">
                  <a-radio-group
                    v-model="form.portalads.fileType"
                    @change="onChangePortal($event, 'fileType')"
                  >
                    <a-radio value="1">
                      {{ $t('portalAuth.type1') }}
                      <a-tooltip
                        placement="topLeft"
                        :title="$t('portalAuth.imgTip', { size: 2.5 })"
                        arrow-point-at-center
                      >
                        <icon-font type="ic-help" class="ic-help-tip" />
                      </a-tooltip>
                    </a-radio>
                    <a-radio value="2">
                      {{ $t('portalAuth.type2') }}
                      <a-tooltip
                        placement="topLeft"
                        :title="$t('portalAuth.videoTip', { size: 10 })"
                        arrow-point-at-center
                      >
                        <icon-font type="ic-help" class="ic-help-tip" />
                      </a-tooltip>
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>

                <a-form-model-item
                  :label="
                    form.portalads.fileType == 1
                      ? $t('portalAuth.type1')
                      : $t('portalAuth.type2')
                  "
                >
                  <a-upload
                    v-if="form.portalads.fileType == 1"
                    :multiple="true"
                    :fileList="fileListAdImg"
                    :beforeUpload="beforeUploaAdvertisementImg"
                    :max-count="3"
                    accept=".jpg,.png,.gif
                    "
                    :showUploadList="false"
                  >
                    <a-button
                      style="margin-bottom: 12px"
                      :disabled="form.portalads.carouselPic.length >= 3"
                      >{{ $t('common.upload') }} </a-button
                    >(1-3 {{ $t('portalAuth.type13') }})
                  </a-upload>

                  <a-upload
                    v-else
                    :multiple="true"
                    :fileList="fileListAd"
                    :beforeUpload="beforeUploaAdvertisementImg"
                    :max-count="1"
                    accept=".mp4,.mkv"
                    :showUploadList="false"
                  >
                    <a-button style="margin-bottom: 12px"
                      >{{ $t('common.upload') }}
                    </a-button>
                  </a-upload>
                </a-form-model-item>

                <div
                  style="display: flex; margin-top: 12px; margin-bottom: 12px"
                  v-if="form.portalads.fileType == 1"
                >
                  <div
                    class="preview-portal-item"
                    :key="index"
                    v-for="(item, index) in form.portalads.carouselPic"
                  >
                    <img class="preview-portal" :src="item" :key="index" />
                    <icon-font
                      type="ic-delete"
                      class="ic-delete"
                      @click="deleteAd(index)"
                    />
                  </div>
                </div>

                <div
                  style="display: flex; margin-top: 12px; margin-bottom: 12px"
                  v-if="
                    form.portalads.fileType == 2 &&
                    (form.portalads.portalFileId || fileListAd.length > 0)
                  "
                >
                  <div class="preview-portal-item" v-if="videoUrl != ''">
                    <video controls width="150" :src="videoUrl"></video>
                    <icon-font
                      type="ic-delete"
                      class="ic-delete"
                      v-if="!form.portalads.portalFileId"
                      @click="deleteAd()"
                    />
                  </div>
                </div>

                <a-form-model-item :label="$t('portalAuth.time')">
                  <a-input-number
                    v-model="form.portalads.durationtime"
                    :min="1"
                    :max="20"
                    placeholder="1-20"
                    @blur="onBlurDurationTime"
                  />
                </a-form-model-item>
                <a-form-model-item :label="$t('portalAuth.skip')">
                  <a-switch v-model="form.portalads.skipStatus"></a-switch>
                </a-form-model-item>
              </template>
            </div>

            <!--广告结束-->
            <!-- 欢迎文字颜色 -->
            <a-form-model-item
              v-if="form.portalSubForm.welcomeType === 'text'"
              :label="$t('portalAuth.welcomeTxtColor')"
            >
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.welcomeTextColor"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.welcomeTextColor" />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>

            <!-- 欢迎文字大小 -->
            <a-form-model-item
              v-if="form.portalSubForm.welcomeType === 'text'"
              :label="$t('portalAuth.welcomeTextSize')"
            >
              <a-slider
                v-model="form.style.welcomeTextSize"
                :default-value="0"
              />
            </a-form-model-item>

            <!-- 按钮颜色 -->
            <a-form-model-item :label="$t('portalAuth.btnColor')">
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.button.color"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.button.color" />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>

            <!-- 按钮字体颜色 -->
            <a-form-model-item :label="$t('portalAuth.btnTxtColor')">
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.button.textColor"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.button.textColor" />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>

            <!-- 链接颜色 -->
            <a-form-model-item :label="$t('portalAuth.linkColor')">
              <a-row type="flex">
                <a-col :span="3">
                  <input
                    type="color"
                    v-model="form.style.linkColor"
                    class="colorPick"
                  />
                </a-col>
                <a-col :span="10">
                  <a-input v-model="form.style.linkColor" />
                </a-col>
              </a-row>
            </a-form-model-item>

            <!-- 文字颜色 -->
            <a-form-model-item :label="$t('portalAuth.txtColorInBox')">
              <a-input-group>
                <a-row :gutter="8">
                  <a-col :span="3">
                    <input
                      type="color"
                      v-model="form.style.text.color"
                      class="colorPick"
                    />
                  </a-col>
                  <a-col :span="10">
                    <a-input v-model="form.style.text.color" />
                  </a-col>
                </a-row>
              </a-input-group>
            </a-form-model-item>
          </a-form-model>
        </div>
        <PortalPreview
          :isBgHorizontal="isBgHorizontal"
          ref="portalPreviewRef"
          :currentPreviewCls="currentPreviewCls"
          :form="form"
          :portalStyle="portalStyle"
          :portalLogo="portalLogo"
          @resetStyle="resetStyle"
        ></PortalPreview>
      </div>
    </CommonPanel>
    <ProtectionModal
      ref="protectionModal"
      @handlecheckProtection="handlecheckProtection"
    />
    <DisclaimerModal
      ref="disclaimerModal"
      :defaultRegDisclaimerTitle="defaultRegDisclaimerTitle"
      :portalSubForm="form.portalSubForm"
      @setDisclaimerMessage="setDisclaimerMessage"
    />
  </div>
</template>

<script>
import { maccApi, requestHttpUploadByForm } from '@utils/index';
import { i18nRender } from '@/locales';
import html2canvas from 'html2canvas';
import CommonPanel from './commonPanel';
import ProtectionModal from './protectionModal';
import DisclaimerModal from './disclaimerModal';
import PortalPreview from './portalPreview.vue';
import { PortalLangs, PortalLangTxts } from './portalLangs.js';
import _ from 'lodash';
// import { VueCropper } from 'vue-cropper';
const defaultLogoUrl = require('@/assets/images/portal/logo.png');
const defaultLogoName = 'Default Logo';
const defaultBgUrl = require('@/assets/images/portal/innerBgDesk.png');
const defaultBgName = 'Default Image';
const defaultLangCode = 'en_US';
export default {
  name: 'portalViewEditor',

  props: {
    portalObj: {
      typeof: Object,
      default: null,
    },
    groupId: Number,
  },

  components: {
    CommonPanel,
    ProtectionModal,
    DisclaimerModal,
    PortalPreview,
    // VueCropper,
  },

  data() {
    return {
      portalLangs: PortalLangs,
      labelCol: { span: 9 },
      wrapperCol: { span: 15 },
      authTypes: ['PASS'],

      currentLangCode: 'en_US', // 跟portal lang对应。
      currentShowLang: '',

      selectedLangs: [
        {
          code: 'en_US',
          name: 'English',
        },
      ],
      videoUrl: '',
      form: {
        // Logo
        hasLogo: true, // ！！不提交仅用于状态
        logo: defaultLogoUrl, //
        logoName: defaultLogoName, //
        restoreLogo: true, // 是否初始logo
        portalads: {
          durationtime: '3',
          skipStatus: false,
          adsStatus: false,
          fileType: '1', //广告轮播图或者视频
          carouselPic: [],
          //  portalFileId
        },

        // Bg
        backgroundType: 'image',
        background: defaultBgUrl, // 背景图片URL
        backgroundName: defaultBgName, //
        backgroundSource: 1, // 判断背景图来源： 1表示用户上传 还是 2表示选择自带的背景
        restoreBackground: true, // 有点奇怪，这里旧版默认是false

        style: {
          logoPosition: 50,
          linkColor: '#ffffff',
          welcomeTextColor: '#ffffff',
          welcomeTextSize: 16,
          welcomeTextFont: 'Calibri', // 字体固定，界面不提供入口
          backgroundColor: '#999999',
          backgroundMaskColor: '#999999', //
          backgroundMaskOpacity: 0, //
          button: {
            position: 10, // 按钮位置，界面不提供入口
            color: '#0066ff',
            textColor: '#ffffff',
            disabledColor: '#E3E3E3', // 禁用按钮颜色，界面不提供入口
            disabledTextColor: '#666666', // 禁用按钮文字颜色，界面不提供入口
          },
          text: {
            color: '#ffffff',
          },
        },

        portals: [this.getPortalByLangCode(defaultLangCode)],
        // 不提交仅用于状态
        portalSubForm: this.getPortalByLangCode(defaultLangCode),
      },

      portalStyle: {
        logoStyle: {},
        bgStyle: {},
        markbgStyle: {},
        wrapperStyle: {},
        btnStyle: {},
        welcomeStyle: {},
        linkStyle: {},
      },

      positionMarks: {
        0: '',
        10: '',
        20: '',
        30: '',
        40: '',
        50: '',
      },

      fileList: [], // Logo图片
      fileList2: [], // 背景图图片
      fileList3: [], // 欢迎图片
      fileListAd: [], //广告视频
      fileListAdImg: [], //广告轮播图

      // 已添加的tab
      // 已添加tab的文字样式
      chooseStyle: {
        color: '#a0a0a0',
        'text-decoration': 'line-through',
      },
      newTabIndex: 1,
      // 截图模式
      model: 'mobile',
      // 截图组件配置
      option: {
        img: 'https://t7.baidu.com/it/u=2291349828,4144427007&fm=193&f=GIF',
        size: 1,
        outputType: 'jpeg',
      },
      option2: {
        img: 'https://t7.baidu.com/it/u=656148390,14962452&fm=193&f=GIF',
        size: 1,
        outputType: 'jpeg',
      },
      option3: {
        img: 'https://t7.baidu.com/it/u=2291349828,4144427007&fm=193&f=GIF',
        size: 1,
        outputType: 'jpeg',
      },
      // 截图返回数据
      previews: {},
      previewMode: 'mobile',
      defaultBackgroundImage: [
        {
          id: 0,
          tooltip: i18nRender('deviceDetail.default'),
          miniUrl: require('@/assets/images/portal/miniBg1.png'),
          imgUrl: defaultBgUrl,
        },
        {
          id: 1,
          name: 'innerBgDesk2.png',
          tooltip: i18nRender('common.smb'),
          miniUrl: require('@/assets/images/portal/miniBg2.png'),
          imgUrl: require('@/assets/images/portal/innerBgDesk2.png'),
        },
        {
          id: 2,
          name: 'innerBgDesk3.png',
          tooltip: i18nRender('common.hotel'),
          miniUrl: require('@/assets/images/portal/miniBg3.png'),
          imgUrl: require('@/assets/images/portal/innerBgDesk3.png'),
        },
        {
          id: 3,
          name: 'innerBgDesk4.png',
          tooltip: i18nRender('common.chain'),
          miniUrl: require('@/assets/images/portal/miniBg4.png'),
          imgUrl: require('@/assets/images/portal/innerBgDesk4.png'),
        },
        {
          id: 4,
          name: 'innerBgDesk5.png',
          tooltip: i18nRender('common.store'),
          miniUrl: require('@/assets/images/portal/miniBg5.png'),
          imgUrl: require('@/assets/images/portal/innerBgDesk5.png'),
        },
      ],
      defaultImgId: 0, //为-1不选择任何自带背景图片，默认用户上传
      checkProtection: false, // 判断是否阅读的数据保护协议
      defaultRegDisclaimerTitle: '', // 用于placehode

      isBgHorizontal: false,
    };
  },

  mounted() {
    this.$EventBus.$on('setAuthTypes', (authTypes) => {
      this.authTypes = authTypes;
    });

    // if (this.portalObj) {
    //   this.initData();
    // }
  },

  destroyed() {
    this.$EventBus.$off('setAuthTypes');
  },

  watch: {
    portalObj: {
      handler: function () {
        if (this.portalObj) {
          this.initData();
        }
      },
      deep: true,
      immediate: true,
    },

    'form.backgroundType': {
      handler(newVal) {
        if (newVal === 'image') {
          this.portalStyle.bgStyle[
            'background-image'
          ] = `url("${this.form.background}")`;
          this.portalStyle.markbgStyle[
            'background'
          ] = `url("${this.form.background}") center`;
        } else {
          this.portalStyle.bgStyle['background-image'] = 'none';
          this.portalStyle.markbgStyle['background'] = 'none';
          this.portalStyle.bgStyle['background-color'] =
            this.form.style.backgroundColor;
        }
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.backgroundColor': {
      handler() {
        if (this.form.backgroundType === 'image') {
          this.portalStyle.bgStyle[
            'background-image'
          ] = `url("${this.form.background}")`;
          this.portalStyle.markbgStyle[
            'background'
          ] = `url("${this.form.background}") center`;
        } else {
          this.portalStyle.bgStyle['background-image'] = 'none';
          this.portalStyle.markbgStyle['background'] = 'none';
          this.portalStyle.bgStyle['background-color'] =
            this.form.style.backgroundColor;
        }
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.background': {
      async handler() {
        if (this.form.backgroundType === 'image') {
          this.isBgHorizontal = await this.checkBgHorizontal(
            this.form.background
          );

          this.portalStyle.bgStyle[
            'background-image'
          ] = `url("${this.form.background}")`;
          this.portalStyle.markbgStyle[
            'background'
          ] = `url("${this.form.background}") center `;
          this.$forceUpdate();
        } else {
          this.portalStyle.bgStyle['background-image'] = 'none';
          this.portalStyle.markbgStyle['background'] = 'none';
          this.portalStyle.bgStyle['background-color'] =
            this.form.style.backgroundColor;
        }
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.logoPosition': {
      handler(newVal, oldVal) {
        this.portalStyle.logoStyle['margin-top'] = `${newVal}px`;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.text.color': {
      handler() {
        this.portalStyle.wrapperStyle['color'] = this.form.style.text.color;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.backgroundMaskColor': {
      handler() {
        var opcaity =
          this.form.style.backgroundMaskOpacity / 100 > 1
            ? 1
            : this.form.style.backgroundMaskOpacity / 100;
        const color = this.form.style.backgroundMaskColor;
        this.portalStyle.wrapperStyle[
          'background-color'
        ] = `rgba(${this.colorToRGB(color)}, ${opcaity})`;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.backgroundMaskOpacity': {
      handler() {
        var opcaity =
          this.form.style.backgroundMaskOpacity / 100 > 1
            ? 1
            : this.form.style.backgroundMaskOpacity / 100;
        const color = this.form.style.backgroundMaskColor;
        this.portalStyle.wrapperStyle[
          'background-color'
        ] = `rgba(${this.colorToRGB(color)}, ${opcaity})`;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.button.color': {
      handler() {
        this.portalStyle.btnStyle['background-color'] =
          this.form.style.button.color;
        this.portalStyle.btnStyle['border-color'] =
          this.form.style.button.color;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.button.textColor': {
      handler() {
        this.portalStyle.btnStyle['color'] = this.form.style.button.textColor;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.welcomeTextSize': {
      handler() {
        this.portalStyle.welcomeStyle['font-size'] = `${
          this.form.style.welcomeTextSize - 8
        }px`;
        this.portalStyle.welcomeStyle['line-height'] = `${
          this.form.style.welcomeTextSize + 4
        }px`;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.welcomeTextColor': {
      handler() {
        this.portalStyle.welcomeStyle['color'] =
          this.form.style.welcomeTextColor;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
    'form.style.linkColor': {
      handler() {
        this.portalStyle.linkStyle['color'] = this.form.style.linkColor;
        this.$refs.portalPreviewRef &&
          this.$refs.portalPreviewRef.forceUpdate();
      },
      immediate: true,
    },
  },
  computed: {
    portalLangObj() {
      const obj = {};
      for (const l of this.portalLangs) {
        obj[l.code] = l.name;
      }
      return obj;
    },

    includeRegister() {
      return this.authTypes.includes('REGISTER') ? true : false;
    },

    /**
     * @description: 这个计算属性方便给弹框内赋值
     * @return {*}
     */
    regDisclaimerTerm() {
      const regDisclaimerTitle = this.form.portalSubForm.regDisclaimerTitle;
      if (regDisclaimerTitle) {
        const arr = this.form.portalSubForm.regDisclaimerTitle.split('###');
        return {
          termCustomer: arr[1],
          termOperation: arr[3],
          termContent: this.form.portalSubForm.regDisclaimerContent,
        };
      } else {
        return {
          termCustomer: 'xxx',
          termOperation: this.form.portalSubForm.registerOperation,
          termContent: '',
        };
      }
    },
    portalLogo() {
      return this.form.logo == 'noLogo' ? defaultLogoUrl : this.form.logo;
    },
    maccUrl() {
      // 原来通过cloud才用location.origin需要修订，专享云就不含有origin
      return location.origin;
    },
    currentPreviewCls() {
      let previewClses = [];
      for (const authType of this.authTypes) {
        switch (authType) {
          case 'PASS':
            previewClses.push('has-one-click');
            break;
          case 'VOUCHER':
            previewClses.push('has-voucher');
            break;
          case 'SMS':
            previewClses.push('has-sms');
            break;
          case 'FIXACCOUNT':
            previewClses.push('has-account');
            break;
          case 'REGISTER':
            previewClses.push('has-register');
            break;
          case 'FACEBOOK':
            previewClses.push('has-facebook');
            break;
        }
      }

      // tommy 24.6.6 需要注册信息允许采集的复选框非强制，所以这个不勾选时，条款不显示
      if (!this.checkProtection) {
        previewClses.push('no-register-private');
      }

      return previewClses.join(' ');
    },
  },
  methods: {
    checkBgHorizontal(bgUrl) {
      var imgtemp = new Image(); //创建一个image对象
      imgtemp.src = bgUrl;
      return new Promise((resolve, reject) => {
        try {
          imgtemp.onload = function () {
            //图片加载完成后执行
            const realWidth = this.width;
            const realHeight = this.height;
            if (realWidth >= realHeight) {
              resolve(true);
            } else {
              resolve(false);
            }
          };
        } catch (e) {
          reject(e);
        }
      });
    },
    initData() {
      const portalObject = _.cloneDeep(this.portalObj);
      const { maccPortalInfo } = portalObject;
      this.authTypes = maccPortalInfo.authType.split(',');

      if (
        maccPortalInfo.logo !== 'noLogo' &&
        !maccPortalInfo.logo.includes('http')
      ) {
        maccPortalInfo.logo = this.maccUrl + maccPortalInfo.logo;
      }

      if (
        maccPortalInfo.logo !== 'noLogo' &&
        /Default|Default Logo/.test(maccPortalInfo.logoName)
      ) {
        maccPortalInfo.logoName = defaultLogoName;
        maccPortalInfo.logo = defaultLogoUrl;
      }
      //背景图片相关
      let restoreBackground = false;
      if (/Default|Default Image/.test(maccPortalInfo.backgroundName)) {
        maccPortalInfo.background = defaultBgUrl;
        restoreBackground = true;
      }

      if (
        maccPortalInfo.backgroundType == 'color' ||
        maccPortalInfo.backgroundSource == 1
      ) {
        this.defaultImgId = -1; //说明上次是用户上传，默认图片设置为-1
      } else if (
        maccPortalInfo.backgroundSource == 2 ||
        maccPortalInfo.backgroundSource == undefined
      ) {
        //backgroundSource == 2：默认上传情况  或  backgroundSource 不存在：旧版直接进行对比判断是否是默认图片
        for (let i = 0; i < this.defaultBackgroundImage.length; i++) {
          if (
            maccPortalInfo.backgroundName == this.defaultBackgroundImage[i].name
          ) {
            this.defaultImgId = this.defaultBackgroundImage[i].id;
            break;
          }
        }
      }
      if (
        maccPortalInfo.background &&
        !maccPortalInfo.background.includes('http')
      ) {
        maccPortalInfo.background = this.maccUrl + maccPortalInfo.background;
      }

      this.form = {
        ...this.form,
        hasLogo: maccPortalInfo.logo !== 'noLogo',
        logo: maccPortalInfo.logo,
        logoName: maccPortalInfo.logoName,

        backgroundType: maccPortalInfo.backgroundType,
        background: maccPortalInfo.background,
        backgroundName: maccPortalInfo.backgroundName,
        backgroundUrl: maccPortalInfo.background,
        backgroundSource: maccPortalInfo.backgroundSource,
        restoreBackground,
      };

      const s = JSON.parse(maccPortalInfo.style);
      s.logoPosition = parseInt(s.logoPosition);
      s.welcomeTextSize = parseInt(s.welcomeTextSize);
      this.form.style = s;

      let portalads = maccPortalInfo.portalads;
      if (portalads) {
        portalads.skipStatus = portalads?.skipStatus == 1;
        portalads.adsStatus = portalads?.adsStatus == 1;
        portalads.fileType = portalads.fileType + '';
      } else {
        portalads = portalads || {
          durationtime: '3',
          skipStatus: false,
          adsStatus: false,
          fileType: '1', //广告轮播图或者视频
        };
      }

      this.form.portalads = portalads;
      if (!this.form.portalads.carouselPic) {
        this.form.portalads.carouselPic = [];
      }
      //  if (portalads.adsStatus) {
      this.dealAdPng(portalads);
      //  }
      const langCodes = [];
      for (const p of maccPortalInfo.portals) {
        langCodes.push(p.language);
        if (p.advert && !p.advert.includes('http')) {
          p.advert = this.maccUrl + p.advert;
        }
      }

      this.form.portals = maccPortalInfo.portals;
      this.currentLangCode = this.form.portals[0].language;
      this.currentShowLang = this.form.portals[0].showLang;
      const newPortal = this.getPortalByLangCode(this.currentLangCode);
      this.form.portalSubForm = {
        ...newPortal,
      };
      if (this.form.portalSubForm.regDisclaimerContent) {
        this.checkProtection = true;
      }

      const langs = [];
      for (const lang of this.portalLangs) {
        if (langCodes.includes(lang.code)) {
          langs.push(lang);
        }
      }
      this.selectedLangs = [...langs];
    },
    async dealAdPng(portalads) {
      if (portalads.fileReloadList == null) return;
      if (portalads.fileType == 1) {
        for (let i = 0; i < portalads.fileReloadList.length; i++) {
          let url = this.maccUrl + portalads.fileReloadList[i];
          let base64url = await this.url2Base64(url);
          this.form.portalads.carouselPic.push(base64url);
        }
      } else {
        for (let i = 0; i < portalads.fileReloadList.length; i++) {
          this.videoUrl = this.maccUrl + portalads.fileReloadList[i];
        }
      }
    },
    url2Base64(url) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        let img = new Image();
        img.setAttribute('crossOrigin', 'anonymous');
        img.src = url;
        img.onload = () => {
          var canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0, img.width, img.height);
          var quality = 0.8;
          //这里的dataurl就是base64类型
          var base64 = canvas.toDataURL('image/png', quality);
          resolve(base64);
        };
      });
    },

    getSelectedClass(item) {
      for (const lang of this.selectedLangs) {
        if (lang.code === item.code) {
          return this.chooseStyle;
        }
      }
      return '';
    },

    /**
     * @description: 重置样式
     * @return {*}
     */
    resetStyle() {
      this.form = {
        ...this.form,
        // Logo
        hasLogo: true, // ！！不提交仅用于状态

        logo: defaultLogoUrl, //
        logoName: defaultLogoName, //
        restoreLogo: true, // 是否初始logo

        portalads: {
          durationtime: '3',
          skipStatus: false,
          adsStatus: false,
          fileType: '1', //广告轮播图或者视频
          carouselPic: [],
        },

        // Bg
        backgroundType: 'image',
        background: defaultBgUrl, // 背景图片URL
        backgroundName: defaultBgName, //
        backgroundSource: 1,
        backgroundUrl: '',
        restoreBackground: true, // 有点奇怪，这里旧版默认是false

        style: {
          logoPosition: 0,
          linkColor: '#ffffff',
          welcomeTextColor: '#ffffff',
          welcomeTextSize: 24,
          welcomeTextFont: 'Calibri', // 字体固定，界面不提供入口
          backgroundColor: '#999999',
          backgroundMaskColor: '#999999', //
          backgroundMaskOpacity: 0, //
          button: {
            position: 10, // 按钮位置，界面不提供入口
            color: '#0066ff',
            textColor: '#ffffff',
            disabledColor: '#E3E3E3', // 禁用按钮颜色，界面不提供入口
            disabledTextColor: '#666666', // 禁用按钮文字颜色，界面不提供入口
          },
          text: {
            color: '#ffffff',
          },
        },
      };
      this.defaultImgId = 0;
    },

    /**
     * @description: 关键步骤，设置的时候将值设置如portal中的对应的值
     * @param {*} e
     * @param {*} portalParam
     * @return {*}
     */
    onChangePortal(e, portalParam) {
      // let index = 0;
      for (const p of this.form.portals) {
        if (p.language === this.currentLangCode) {
          p[portalParam] = e.target.value;
          // break;
        }
        // index++;
      }

      // this.form.portals[index][portalParam] = e.target.value;
    },
    //上传广告图标或者视频
    async uploadAd() {
      if (this.form.portalads.fileType == 2) {
        let api = `${maccApi.SAMTRANSFER_UPLOADFOR_FILE}?groupId=${this.groupId}&fileType=${this.form.portalads.fileType}`;
        if (this.form.portalads.portalFileId) {
          if (this.fileListAd.length == 0 && this.videoUrl != '') {
            return true;
          }
          if (this.fileListAd.length == 0 && this.videoUrl == '') {
            this.$message.warning(this.$t('userManage.printUploadSelectVideo'));
            return false;
          }
          api = `${api}&portalFileId=${this.form.portalads.portalFileId}`;
        }
        if (this.videoUrl == '') {
          this.$message.warning(this.$t('userManage.printUploadSelectVideo'));
          return false;
        }
        let file = this.fileListAd[0];
        this.uploadData = {
          uploadData: JSON.stringify({
            api: api,
            module: 'default',
            fileName: 'file',
            contentType: 'multipart/form-data', // 此接口必须设置contentType
          }),
        };
        let params = {
          file: file,
          uploadData: this.uploadData.uploadData,
        };

        let res = await requestHttpUploadByForm(params);
        if (res && res.code == 0) {
          console.log(res);
          this.form.portalads.portalFileId = res.data.data.portalFileId;
        } else {
          console.log(res);
          return false;
        }
        this.form.portalads.carouselPic = [];
        return true;
      }
      return true;
    },

    onBlurDurationTime() {
      if (!this.form.portalads.durationtime) {
        this.form.portalads.durationtime = 1;
      }
    },

    /**
     * @description: 获取配置。portal的保存包括两个部分view和auth，保存时获取配置
     * @return {*}
     */
    async getConf() {
      const self = this;
      self.previewMode = 'mobile'; // 保存到时候切换为移动端
      //判断背景图来源： 1表示用户上传 还是 2表示选择自带的背景
      this.form.backgroundSource = this.defaultImgId === -1 ? 1 : 2;

      if (this.includeRegister) {
        // tommy 2024.6.6 有勾选的时候才需要判断不为空
        if (this.checkProtection) {
          for (const p of this.form.portals) {
            if (!p.regDisclaimerContent) {
              this.$warning({
                title: this.$t('common.tip'),
                okText: this.$t('common.ok'),
                content: this.$t('portalAuth.protectNotNull', [
                  ` (${this.portalLangObj[p.language]})`,
                ]),
              });

              return { valid: false };
            }
          }
        }
      }

      // tommy 231003 增加默认语言选项
      for (const p of this.form.portals) {
        if (this.currentShowLang === '') {
          delete p.showLang;
        } else {
          p.showLang = this.currentShowLang;
        }
      }

      if (this.form.portalads.adsStatus) {
        if (this.form.portalads.fileType == 2) {
          this.form.portalads.carouselPic = [];
          if (this.fileListAd.length == 0 && this.videoUrl == '') {
            this.$message.warning(this.$t('userManage.printUploadSelectVideo'));
            return { valid: false };
          }
          if (this.videoUrl == '') {
            this.$message.warning(this.$t('userManage.printUploadSelectVideo'));
            return { valid: false };
          }
        }

        if (
          this.form.portalads.fileType == 1 &&
          this.form.portalads.carouselPic.length == 0
        ) {
          this.$message.warning(this.$t('portalAuth.selectPNG'));
          return { valid: false };
        }
      }
      //修复 选择welcome image 未上传图片也能保存
      if (
        this.form.portals[0].welcomeType === 'image' &&
        this.form.portals[0].advert == this.maccUrl
      ) {
        this.$message.warning(this.$t('portalAuth.uploadWelcomePic'));
        return { valid: false };
      }

      //用户选择默认4张图片
      if (this.form.backgroundSource === 2) {
        let blob = null;
        fetch(
          window.location.origin +
            this.defaultBackgroundImage[this.defaultImgId].imgUrl
        )
          .then((response) => response.blob())
          .then((res) => {
            this.beforeUploadBg(res, true);
          });
      }
      if (this.form.portalads.adsStatus && this.form.portalads.fileType == 2) {
        await this.uploadAd();
      }
      if (!this.form.portalads.durationtime) {
        this.form.portalads.durationtime = 1;
      }

      return new Promise((resolve) => {
        // tommy 24.6.7 截图的时候转为mobile模式
        this.$refs.portalPreviewRef.choosePreviewMode('mobile');

        // tommy 24.6.18【认证配置】portal的电脑预览缩略图，与实际不符合
        setTimeout(() => {
          html2canvas(this.$refs.portalPreviewRef.getPhonePreviewRef(), {
            useCORS: true, //保证跨域图片的显示
            allowTaint: false,
          }).then(function (canvas) {
            // 缩略图用低画质
            let canvasUrl = canvas.toDataURL('image/jpeg', 0.8);
            // self.$parent.setSubmitingStatus(self.$t('portalAuth.submiting'));

            const { portalSubForm, sid, authPhone, authToken, ...res } =
              self.form;
            res.valid = true;
            res.snapShot = canvasUrl;
            res.style = JSON.stringify(self.form.style);
            res.css = self.getCssFromStyle();

            if (res.background.includes('data:')) {
              res.backgroundUrl = '';
            } else {
              res.background = '';
            }

            if (!res.hasLogo) {
              res.logo = 'noLogo';
            }
            resolve(res);
          });
        }, 500);
      });
    },

    getCssFromStyle() {
      var textColor = this.form.style.text.color;
      var logoPosition = this.form.style.logoPosition || 0;
      if (20 == logoPosition) {
        logoPosition = 0.36;
      } else if (40 == logoPosition) {
        logoPosition = 0.36 * 2;
      } else if (60 == logoPosition) {
        logoPosition = 0.36 * 3;
      }
      var buttonPosition = this.form.style.button.position;
      if (10 == buttonPosition) {
        buttonPosition = 0.2;
      } else if (20 == buttonPosition) {
        buttonPosition = 0.2 * 2;
      } else if (30 == buttonPosition) {
        buttonPosition = 0.2 * 3;
      }
      var welcomeTextSize = this.form.style.button.welcomeTextSize * 0.02;
      var welcomeTextLineHeight = welcomeTextSize + 4;
      // if (this.model === 'mobile') welcomeTextSize *= 0.0257;
      // else welcomeTextSize *= 0.02;
      welcomeTextLineHeight *= 0.0278;

      var bgOpcaity =
        this.form.style.backgroundMaskOpacity / 100 > 1
          ? 1
          : this.form.style.backgroundMaskOpacity / 100;
      const bgColor = this.form.style.backgroundMaskColor;

      var cssStr = '';
      // Logo Position
      cssStr += `.logoPosition { margin-top: ${logoPosition.toFixed(2)}rem; }`;
      // Button Position
      cssStr += `.buttonPosition { margin-top: ${buttonPosition.toFixed(
        2
      )}rem; }`;
      // Button Color
      cssStr += `.portal-login-btn { background-color: ${this.form.style.button.color}; }`;
      // Button Text Color
      cssStr += `.portal-login-btn span { color: ${this.form.style.button.textColor}; }`;
      // Link Color
      cssStr += `.e_teco2 { color: ${this.form.style.linkColor}; }`;
      // Text Color
      cssStr += `.marketText { color: ${textColor}; }`;
      cssStr += `.e_teco1 { color: ${textColor}; }`;
      cssStr += `.copyRightDiv p { color: ${textColor}; }`;
      cssStr += `.voucher_code input { border-color: ${textColor}; }`;
      cssStr += `.voucher_codeText_input::-webkit-input-placeholder { color: ${textColor}; }`;
      cssStr += `.remainLabel, .remainVal { color: ${textColor}; }`;
      cssStr += `.successTitle, .successTip { color: ${textColor}; }`;
      // Welcome Message Text Color & Size
      //cssStr += (".welcomeText { color: " + $("#high_welMsgTextColor").val() + "; font-family: " + $("#high_welMsgTextFont").val() + "; font-size: " + welcomeTextSize + "rem; line-height: " + welcomeTextLineHeight + "rem; }");
      cssStr += `.welcomeText { color: ${this.form.style.welcomeTextColor}; font-size: ${welcomeTextSize}rem; line-height: ${welcomeTextLineHeight}rem; }`;
      // Background Mask Color & Opacity
      if (this.form.backgroundType === 'image') {
        cssStr += '.mobilePage_bg { background-color: transparent }';
        cssStr += '.mobilePage_bg_desk { background-color: transparent }';
      } else {
        cssStr += `.mobilePage_bg { background-image: none; background-color: ${this.form.style.backgroundColor}}`;
        cssStr += `.mobilePage_bg_desk { background-image: none; background-color: ${this.form.style.backgroundColor} }`;
      }

      cssStr += `.mobilePage { background-color: rgba(${this.colorToRGB(
        bgColor
      )}, ${bgOpcaity})}`;
      cssStr += `.mmobilePage_desk { background-color: rgba(${this.colorToRGB(
        bgColor
      )}, ${bgOpcaity})}`;

      return cssStr;
    },

    savePortal() {
      const params = {
        logo: this.form.logo,
        logoName: this.form.logoName,
      };
    },
    // 把16进制颜色转换成rgb格式
    colorToRGB(color) {
      var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/g;
      var sColor = color.toLowerCase();
      if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
          let sColorNew = '#';
          for (let i = 1; i < 4; i += 1) {
            sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
          }
          sColor = sColorNew;
        }

        //处理六位的颜色值
        let sColorChange = [];
        for (let i = 1; i < 7; i += 2) {
          sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)));
        }
        return sColorChange.join(',');
      } else {
        return color;
      }
    },
    beforeUploadLogo(file) {
      let fileSize = file.size / 1024 / 1024;
      if (fileSize > 1.5) {
        this.$message.warning(
          this.$t('userManage.printUploadLogoTip1', { size: '1.5' })
        );
        return false;
      }

      // 这里读取文件主要是为了解码跟获取文件的尺寸
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        let img = new Image();
        img.src = reader.result;
        img.onload = () => {
          let width = img.width;
          let height = img.height;
          if (width > 750 || height > 300) {
            this.$message.warning(
              this.$t('userManage.printUploadLogoTip2', {
                width: 750,
                height: 300,
              })
            );

            return false;
          }
          this.form.logo = reader.result;
          this.form.logoName = file.name;
          this.form.restoreLogo = false;
        };
      };
      return false;
    },

    beforeUploadBg(file, flag) {
      console.log(file);
      let fileSize = file.size / 1024 / 1024;
      if (fileSize > 2.5) {
        this.$message.warning(
          this.$t('userManage.printUploadLogoTip1', { size: '2.5' })
        );
        return false;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        let img = new Image();
        img.src = reader.result;
        img.onload = () => {
          this.form.background = reader.result;
          this.defaultImgId = flag == true ? this.defaultImgId : -1; //用户上传图片时才改变 defaultimg
          this.form.backgroundName =
            flag == true
              ? this.defaultBackgroundImage[this.defaultImgId].name
              : file.name;
          this.form.restoreBackground = false;
        };
      };
      return false;
    },

    beforeUploadWelcomeImg(file) {
      let fileSize = file.size / 1024 / 1024;
      if (fileSize > 1.5) {
        this.$message.warning(
          this.$t('userManage.printUploadLogoTip1', { size: '1.5' })
        );
        return false;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        let img = new Image();
        img.src = reader.result;
        img.onload = () => {
          let width = img.width;
          let height = img.height;
          if (width > 1080 || height > 1920) {
            this.$message.warning(
              this.$t('userManage.printUploadLogoTip2', {
                width: 1080,
                height: 1920,
              })
            );
            return false;
          }
          this.form.portalSubForm.advert = reader.result;
          this.form.portalSubForm.advertName = file.name;

          for (const p of this.form.portals) {
            if (p.language === this.currentLangCode) {
              p['advert'] = reader.result;
            }
          }
        };
      };
      return false;
    },
    //广告轮播图或者视频上传
    beforeUploaAdvertisementImg(file) {
      if (this.form.portalads.fileType == 1) {
        this.fileListAdImg = [...this.fileListAdImg, file];
        let fileSize = file.size / 1024 / 1024;
        if (fileSize > 2.5) {
          this.$message.warning(
            this.$t('userManage.printUploadLogoTip1', { size: '2.5' })
          );
          return false;
        }
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          let img = new Image();
          img.src = reader.result;
          img.onload = () => {
            this.form.portalads.carouselPic.push(reader.result);
          };
        };
      } else {
        let fileSize = file.size / 1024 / 1024;
        if (fileSize > 10) {
          this.$message.warning(
            this.$t('userManage.printUploadLogoTip3', { size: '10' })
          );
          return false;
        }
        this.videoUrl = URL.createObjectURL(file);
        this.fileListAd = [file];
      }

      return false;
    },
    //删除轮播图
    deleteAd(index) {
      if (this.form.portalads.fileType == 1) {
        this.form.portalads.carouselPic.splice(index, 1);
      } else {
        this.fileListAd = [];
        this.videoUrl = '';
      }
    },

    // 图片上传
    imgUploadChange(info) {},
    // 视频上传
    videoUploadChange(info) {},
    // 获取rgba
    backMaskColChange(value) {
      var arr = [];
      const str = value.slice(5);
      const str1 = str.slice(0, str.length - 1);
      arr = str1.split(',');
      console.log(arr);
      this.form.backgroundMaskOpacity = arr[3] * 100 + '%';
      this.form.backgroundMaskColor = this.olorRGB2Hex(
        arr[0] * 1,
        arr[1] * 1,
        arr[2] * 1
      );
    },
    // rgb转hex
    olorRGB2Hex(r, g, b) {
      let hex =
        '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
      console.log(hex);
      return hex;
    },

    getPortalByLangCode(langCode) {
      const defaultObj = {
        language: langCode,
        welcomeType: 'text',
        welcome: '',
        advert: '', // welcome图片
        advertName: '',

        marketMessage: '',
        tcSubTxt1: PortalLangTxts[langCode]['teco1'], // 只是为了显示不提交
        tcSubTxt2: PortalLangTxts[langCode]['teco2'],
        tc: '',
        copyRight: '',
        accountTitleShown: true,
        voucherTitleShown: true,
        oneclickBtnTxt: PortalLangTxts[langCode]['connect'],
        or: PortalLangTxts[langCode]['or'],

        voucherInputTitle: PortalLangTxts[langCode]['voucher_login'],
        accesscodePlacehold: PortalLangTxts[langCode]['accesscode'],
        voucherLoginBtnTxt: PortalLangTxts[langCode]['login'],
        voucherBtnTxt: PortalLangTxts[langCode]['voucher_login'],

        accountInputTitle: PortalLangTxts[langCode]['account_login'],
        accountPlacehold: PortalLangTxts[langCode]['account'],
        passwordPlacehold: PortalLangTxts[langCode]['password'],
        accountLoginBtnTxt: PortalLangTxts[langCode]['login'],
        accountBtnTxt: PortalLangTxts[langCode]['account_login'],

        facebookBtnTxt: PortalLangTxts[langCode]['fb_login'],

        phoneTitleShown: true,
        phoneInputTitle: PortalLangTxts[langCode]['sms'],
        phonePlacehold: PortalLangTxts[langCode]['sms_phone'],
        phoneCodeGetTip: PortalLangTxts[langCode]['sms_code_btn'],
        phoneCodePlaceholder: PortalLangTxts[langCode]['sms_code'],
        phoneLoginBtnTxt: PortalLangTxts[langCode]['login'],
        phoneBtnTxt: PortalLangTxts[langCode]['sms'],

        registerTitleShown: true,
        registerInputTitle: PortalLangTxts[langCode]['register_title'],
        registerEmailPlacehold: PortalLangTxts[langCode]['register_email'],
        registerPhonePlacehold: PortalLangTxts[langCode]['register_phone'],
        registerUserPlacehold: PortalLangTxts[langCode]['register_username'],
        registerLoginBtnTxt: PortalLangTxts[langCode]['register_title'],
        registerBtnTxt: PortalLangTxts[langCode]['register_btn'],
        regDisclaimerTitle: PortalLangTxts[langCode]['register_send_me'],
        regDisclaimerContent: '',
        registerToggleBtnTxt: PortalLangTxts[langCode]['register_toggle'], // 注册切换文字，直接提交，页面不编辑
      };

      if (this.form && this.form.portals) {
        for (const p of this.form.portals) {
          if (p.language === this.currentLangCode) {
            if (!p.regDisclaimerTitle || p.regDisclaimerTitle === '') {
              p.regDisclaimerTitle =
                PortalLangTxts[langCode]['register_send_me'];
            }

            // tommy 20231003 读取默认语言的配置
            if (p.language === this.currentShowLang) {
              p.isShowLang = true;
            } else {
              p.isShowLang = false;
            }

            // 因为t&c1和t&2的文字不提交的，所以这里需要先取到，然后再用已配置的赋值
            return {
              ...defaultObj,
              ...p,
            };
          }
        }
        return defaultObj; // 新增一个语言的时候，这时这个语言在portals中没有
      } else {
        return defaultObj; // 新增portal的时候，这时整个form.portals都是空的
      }
    },

    /**
     * @description: 添加语言Tab
     * @return {*}
     */
    onClickLangPop(lang) {
      for (const l of this.selectedLangs) {
        if (l.code === lang.code) {
          return;
        }
      }

      this.selectedLangs.push(lang); // tab增加这个内容
      this.currentLangCode = lang.code; // 当前语言编号设定

      const newPortal = this.getPortalByLangCode(lang.code);
      this.form.portals.push(newPortal); // 表单数据增加
      this.form.portalSubForm = {
        ...newPortal,
      };
      this.$forceUpdate();
    },

    /**
     * @description: 更改语言提示
     * @param {*} checked
     * @return {*}
     */
    onChangeShowLang(checked) {
      if (checked) {
        this.currentShowLang = this.currentLangCode; // 当前语言编号设定
      } else {
        this.currentShowLang = '';
      }
    },

    /**
     * @description: 删除语言Tab
     * @return {*}
     */
    onEditLangTab(langCode) {
      let index = 0;
      for (const lang of this.selectedLangs) {
        if (lang.code === langCode) {
          break;
        }
        index++;
      }
      this.selectedLangs.splice(index, 1);
      this.form.portals.splice(index, 1);
      this.currentLangCode = this.selectedLangs[0].code;
      const newPortal = this.getPortalByLangCode(this.currentLangCode);
      this.form.portalSubForm = {
        ...newPortal,
      };
      this.$forceUpdate();
    },

    /**
     * @description: 切换语言Tab
     * @param {*} langCode
     * @return {*}
     */
    onChangeLangTab(langCode) {
      this.currentLangCode = langCode;

      const newPortal = this.getPortalByLangCode(this.currentLangCode);
      this.form.portalSubForm = {
        ...newPortal,
      };
      this.$forceUpdate();
    },

    /**
     * @description: 选择背景图片
     * @param {*} img
     * @return {*}
     */
    onSelectSceneBg(img) {
      this.defaultImgId = img.id;
      this.form.background = img.imgUrl;
      this.$refs.portalPreviewRef.forceUpdate();
    },

    /**
     * @description: 上传背景图片
     * @param {*} info
     * @return {*}
     */
    onChangeBackground(info) {
      //当用户上传完又删除时
      if (info.fileList.length === 0) {
        this.resetDefaultImg();
      }
      this.$refs.portalPreviewRef.forceUpdate();
    },

    resetDefaultImg() {
      this.form.background = defaultBgUrl;
      this.form.backgroundName = defaultBgName;
      this.defaultImgId = 0;
    },
    showDisclaimerModal() {
      if (!this.checkProtection) {
        this.$message.warn(this.$t('portalAuth.protectTip'));
        return false;
      }

      this.defaultRegDisclaimerTitle =
        PortalLangTxts[this.currentLangCode]['register_send_me'];
      this.$refs.disclaimerModal.show();
    },
    setDisclaimerMessage(msg) {
      const { disclaimerTitle, disclaimerContent } = msg;

      this.form.portalSubForm.regDisclaimerTitle = disclaimerTitle;
      this.form.portalSubForm.regDisclaimerContent = disclaimerContent;

      // 这里发现对portalSubForm直接赋值无法变更portals的值，通过model方式才可以
      for (const p of this.form.portals) {
        if (p.language === this.currentLangCode) {
          p.regDisclaimerTitle = disclaimerTitle;
          p.regDisclaimerContent = disclaimerContent;
        }
      }
    },
    handlecheckProtection(e) {
      if (typeof e == 'object') {
        if (this.checkProtection) {
          this.checkProtection = false;
          this.form.portalSubForm.regDisclaimerContent = '';

          // 这里发现对portalSubForm直接赋值无法变更portals的值，通过model方式才可以
          for (const p of this.form.portals) {
            if (p.language === this.currentLangCode) {
              p.regDisclaimerContent = '';
            }
          }
        } else {
          this.$refs.protectionModal.show(true);
        }
      } else {
        if (e != true) return;
        this.checkProtection = e;
      }
    },
    showPersonDataModal(e) {
      // console.log('%O', this.$refs.protectionModal);
      e.preventDefault();
      this.$refs.protectionModal.show(false);
    },
  },
};
</script>

<style lang="less" scoped>
.lang-wrapper {
  overflow-y: auto;
  max-height: 480px;
  padding: 16px;
  padding-bottom: 0;
  border: 1px solid #e8e8e8;
  border-top: 0;
  margin-bottom: 16px;
  /deep/.ant-form-item label {
    line-height: 1.5;
  }
}

.top {
  position: relative;
  .line {
    position: absolute;
    width: 4px;
    height: 16px;
    left: 0px;
    top: calc(50% - 16px / 2);
    background: #2b6aed;
    border-radius: 1px;
  }
  .title {
    font-family: 'Inter';
    font-style: normal;
    font-weight: 700;
    font-size: 16px;
    line-height: 24px;
    color: #1d2129;
    margin-left: 20px;
  }
}
.content {
  font-family: 'Inter';
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 24px;
  color: #1d2129;
  display: flex;
  .left {
    width: 480px;
    .colorPick {
      cursor: pointer;
      width: 30px;
      height: 30px;
      border: 1px solid rgba(0, 0, 0, 0.2);
      border-radius: 2px;
    }
    .tabs {
      position: relative;
      .language {
        cursor: pointer;
        color: red;
        background-color: #2b6aed;
      }
      .language:hover {
        color: rgb(55, 106, 220);
      }
      .tui-factory-price {
        font-size: 24rpx;
        color: #a0a0a0;
        text-decoration: line-through;
        padding-left: 12rpx;
      }
    }
  }
}
.content {
  /deep/ .ant-form-item {
    margin-bottom: 8px;
  }
  /deep/ .ant-form-item-label,
  /deep/ .ant-form-item-control {
    line-height: 32px;
  }
  /deep/ .ant-tabs-bar {
    margin: 0;
  }
  h3 {
    margin-top: 16px;
  }
}
.panel-title {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}
.panel-title-mark {
  display: inline-block;
  margin-right: 8px;
  width: 4px;
  height: 16px;
  background: #2067ec;
}
.panel-title-txt {
  font-size: 16px;
  line-height: 20px;
  align-items: center;
  color: #000000;
}

.preview-add-lang {
  position: absolute;
  top: 7px;
  right: 0;
  cursor: pointer;
  width: 20px;
  height: 20px;
  color: rgba(0, 0, 0, 0.65);
  border: 1px solid rgb(232, 232, 232);
  border-radius: 2px;
  padding: 0;
  line-height: 18px;
}

.scene-bg-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 10px;
}
.scene-bg-wrapper div:hover {
  border-color: #548dff;
}

.div-textarea {
  margin-bottom: 4px;
  min-height: 32px;
  border-radius: 4px;
  padding: 4px 11px;
  max-width: 100%;
  line-height: 1.5;

  &.disclaimer-warning {
    border: 1px solid @error-color;
    color: @error-color;
  }
  &.disclaimer-content {
    border: 1px solid #d9d9d9;
    color: @theme-color;
  }
}
.preview-portal-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-right: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  padding: 8px;
  .ic-delete {
    cursor: pointer;
    color: #d9d9d9;
    margin-left: 24px;
  }
}
.preview-portal {
  width: 80px;
  height: 60px;
  align-items: center;
  display: flex;
  justify-content: center;
}
</style>
